{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "91b43b0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import netCDF4 as nc\n",
    "# 打开 netCDF 文件\n",
    "file_path = r'D:\\\\ABiomass\\\\GFAS\\\\GFAS20131.nc'\n",
    "nf = nc.Dataset(file_path, 'r')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d1529faa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['valid_time', 'latitude', 'longitude', 'co2fire'])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nf.variables.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b8509411",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<class 'netCDF4._netCDF4.Variable'>\n",
       "float32 co2fire(valid_time, latitude, longitude)\n",
       "    _FillValue: nan\n",
       "    GRIB_paramId: 210080\n",
       "    GRIB_dataType: ga\n",
       "    GRIB_numberOfPoints: 6480000\n",
       "    GRIB_typeOfLevel: surface\n",
       "    GRIB_stepUnits: 1\n",
       "    GRIB_stepType: avg\n",
       "    GRIB_gridType: regular_ll\n",
       "    GRIB_uvRelativeToGrid: 0\n",
       "    GRIB_NV: 0\n",
       "    GRIB_Nx: 3600\n",
       "    GRIB_Ny: 1800\n",
       "    GRIB_cfName: unknown\n",
       "    GRIB_cfVarName: co2fire\n",
       "    GRIB_gridDefinitionDescription: Latitude/Longitude Grid\n",
       "    GRIB_iDirectionIncrementInDegrees: 0.1\n",
       "    GRIB_iScansNegatively: 0\n",
       "    GRIB_jDirectionIncrementInDegrees: 0.1\n",
       "    GRIB_jPointsAreConsecutive: 0\n",
       "    GRIB_jScansPositively: 0\n",
       "    GRIB_latitudeOfFirstGridPointInDegrees: 89.95\n",
       "    GRIB_latitudeOfLastGridPointInDegrees: -89.95\n",
       "    GRIB_longitudeOfFirstGridPointInDegrees: 0.05\n",
       "    GRIB_longitudeOfLastGridPointInDegrees: 359.95\n",
       "    GRIB_missingValue: 3.4028234663852886e+38\n",
       "    GRIB_name: Wildfire flux of Carbon Dioxide\n",
       "    GRIB_shortName: co2fire\n",
       "    GRIB_totalNumber: 0\n",
       "    GRIB_units: kg m**-2 s**-1\n",
       "    long_name: Wildfire flux of Carbon Dioxide\n",
       "    units: kg m**-2 s**-1\n",
       "    standard_name: unknown\n",
       "    GRIB_number: 0\n",
       "    GRIB_surface: 0.0\n",
       "    coordinates: valid_time latitude longitude\n",
       "unlimited dimensions: \n",
       "current shape = (365, 1800, 3600)\n",
       "filling on"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#查看一下time的属性\n",
    "nf.variables['co2fire']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "757d500a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 读取 CO2 数据和日期变量\n",
    "fire_modis_CO2 = nf.variables['co2fire'][:]  # shape (365, 1799, 3600)\n",
    "date_var = nf.variables['valid_time'][:]  # 日期变量 (例如：20130101)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2daeb4ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 将日期变量转换为字符串格式\n",
    "dates_str = date_var.astype(str)\n",
    "\n",
    "# 使用 pandas 将字符串格式的日期转换为日期对象\n",
    "dates = pd.to_datetime(dates_str, format='%Y%m%d')\n",
    "\n",
    "# 将日期转换为 DataFrame，以便分组处理\n",
    "dates_df = pd.DataFrame({\n",
    "    'date': dates,\n",
    "    'year': dates.year,\n",
    "    'month': dates.month\n",
    "})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "fc40ee58",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 准备一个空数组用于存储逐月平均值\n",
    "monthly_CO2 = np.zeros((12, fire_modis_CO2.shape[1], fire_modis_CO2.shape[2]))\n",
    "\n",
    "# 遍历每个月，计算每个月的平均值\n",
    "for month in range(1, 13):\n",
    "    # 找到当前月的数据索引\n",
    "    month_idx = dates_df[dates_df['month'] == month].index\n",
    "    \n",
    "    # 取该月的CO2数据并进行平均\n",
    "    monthly_CO2[month-1, :, :] = np.nansum(fire_modis_CO2[month_idx, :, :], axis=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ebb97fab",
   "metadata": {},
   "outputs": [],
   "source": [
    "from netCDF4 import Dataset\n",
    "\n",
    "# 创建新的 netCDF 文件\n",
    "new_ncfile = Dataset('D:\\\\ABiomass\\\\FINN\\\\modis\\\\2013\\\\FINNmonthly_CO2_2013.nc', 'w', format='NETCDF4')\n",
    "\n",
    "# 定义维度\n",
    "new_ncfile.createDimension('lat', fire_modis_CO2.shape[1])\n",
    "new_ncfile.createDimension('lon', fire_modis_CO2.shape[2])\n",
    "new_ncfile.createDimension('month', 12)\n",
    "\n",
    "# 创建变量\n",
    "lat = new_ncfile.createVariable('lat', 'f4', ('lat',))\n",
    "lon = new_ncfile.createVariable('lon', 'f4', ('lon',))\n",
    "month_var = new_ncfile.createVariable('month', 'i4', ('month',))\n",
    "CO2_var = new_ncfile.createVariable('CO2', 'f4', ('month', 'lat', 'lon'))\n",
    "\n",
    "# 给变量赋值\n",
    "lat[:] = nf.variables['lat'][:]\n",
    "lon[:] = nf.variables['lon'][:]\n",
    "month_var[:] = np.arange(1, 13)\n",
    "CO2_var[:, :, :] = monthly_CO2\n",
    "\n",
    "# 关闭文件\n",
    "new_ncfile.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "936d5bf2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 打开 netCDF 文件\n",
    "file_path1 = r'D:\\\\ABiomass\\\\FINN\\\\modisviirs\\\\2013\\\\FINNmonthlyvirrs_CO2_2013.nc'\n",
    "nf1 = nc.Dataset(file_path1, 'r')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "e1ec9e1f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['lat', 'lon', 'month', 'CO2'])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nf1.variables.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "a1f1fcfc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<class 'netCDF4._netCDF4.Variable'>\n",
       "float32 CO2(month, lat, lon)\n",
       "unlimited dimensions: \n",
       "current shape = (12, 1799, 3600)\n",
       "filling on, default _FillValue of 9.969209968386869e+36 used"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#查看一下time的属性\n",
    "nf1.variables['CO2']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "436fc92d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
